咒語:創建一個問卷調查頁面,使用 Material-UI 的表單、單選框、多選框等組件,允許用戶回答調查問題。 以調查喜愛的食物為例子 並把儲存的資料存成一個table展現
可以有單選 多選 儲存用戶的喜好並存成表格備用
import React, { useState } from "react";
import {
Container,
Paper,
Typography,
FormControl,
FormControlLabel,
Radio,
RadioGroup,
Checkbox,
FormGroup,
Button,
Table,
TableContainer,
TableHead,
TableRow,
TableCell,
TableBody,
FormLabel
} from "@mui/material";
function FoodSurvey() {
const [foodPreference, setFoodPreference] = useState("");
const [selectedFoods, setSelectedFoods] = useState([]);
const [surveyData, setSurveyData] = useState([]);
const foods = ["披薩", "漢堡", "炸雞", "意大利面", "壽司", "沙拉", "其他"];
const handleFoodPreferenceChange = (event) => {
setFoodPreference(event.target.value);
};
const handleFoodSelection = (food) => {
if (selectedFoods.includes(food)) {
setSelectedFoods(
selectedFoods.filter((selectedFood) => selectedFood !== food)
);
} else {
setSelectedFoods([...selectedFoods, food]);
}
};
const handleSubmit = () => {
// 將用戶的食物偏好和選擇的食物存儲在 surveyData 中
const newData = {
preference: foodPreference,
selectedFoods: selectedFoods.join(", ")
};
setSurveyData([...surveyData, newData]);
// 清空選擇
setFoodPreference("");
setSelectedFoods([]);
};
return (
<Container>
<Paper elevation={3} style={{ padding: "20px" }}>
<Typography variant="h4" gutterBottom>
食物喜好調查
</Typography>
<form>
<FormControl component="fieldset" sx={{ marginBottom: "20px" }}>
<FormLabel component="legend">您更喜歡哪種食物類型?</FormLabel>
<RadioGroup
aria-label="foodPreference"
name="foodPreference"
value={foodPreference}
onChange={handleFoodPreferenceChange}
>
{foods.map((food) => (
<FormControlLabel
key={food}
value={food}
control={<Radio />}
label={food}
/>
))}
</RadioGroup>
</FormControl>
<FormControl component="fieldset" sx={{ marginBottom: "20px" }}>
<FormLabel component="legend">請選擇您喜歡的食物:</FormLabel>
<FormGroup>
{foods.map((food) => (
<FormControlLabel
key={food}
control={
<Checkbox
checked={selectedFoods.includes(food)}
onChange={() => handleFoodSelection(food)}
/>
}
label={food}
/>
))}
</FormGroup>
</FormControl>
<Button variant="contained" color="primary" onClick={handleSubmit}>
提交
</Button>
</form>
</Paper>
{surveyData.length > 0 && (
<div style={{ marginTop: "20px" }}>
<Typography variant="h5" gutterBottom>
調查結果
</Typography>
<TableContainer component={Paper}>
<Table>
<TableHead>
<TableRow>
<TableCell>食物類型</TableCell>
<TableCell>喜歡的食物</TableCell>
</TableRow>
</TableHead>
<TableBody>
{surveyData.map((data, index) => (
<TableRow key={index}>
<TableCell>{data.preference}</TableCell>
<TableCell>{data.selectedFoods}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</TableContainer>
</div>
)}
</Container>
);
}
export default FoodSurvey;
最後就可以 調查大家的喜好 周末訂餐了